package com.qqt;

import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReflectUtil {
    public static <T> List<Field> fields(Class<T> cla){
        List<Field> fields = new ArrayList<>();
        for(Class clazz=cla;clazz!=Object.class;clazz=clazz.getSuperclass()) {
            for (Field declaredField : clazz.getDeclaredFields()) {
                fields.add(declaredField);
            }
        }
        return fields;
    }

    @SneakyThrows
    public static <T> T mapTranEntity(Map<String,Object> map ,Class<T> clazz){
        T  obj = clazz.newInstance();
        List<Field> fields = ReflectUtil.fields(clazz);
        for (Field field : fields) {
            setField(map.get(field.getName()),field,obj);
        }
        return obj;
    }
    @SneakyThrows
    public static Map<String,Object> entityTranMap(Object obj){
        List<Field> fields = fields(obj.getClass());
        Map<String,Object> map = new HashMap<>();
        for (Field field : fields) {
            field.setAccessible(true);
            Object value = field.get(obj);
            if(value!=null){
                map.put(field.getName(),value);
            }
        }
        return map;
    }


    @SneakyThrows
    public static <T> T resultSetTransEntity(ResultSet rs,Class<T> clazz){
        T instance = clazz.newInstance();
        while(rs.next()){
            List<Field> fieldList = ReflectUtil.fields(clazz);
            for (Field field : fieldList) {
                if(field.getType().equals(String.class)){
                    setField(rs.getString(field.getName()),field,instance);
                }
                if(field.getType().equals(Integer.class)){
                    setField(rs.getInt(field.getName()),field,instance);
                }
                if(field.getType().equals(Long.class)){
                    setField(rs.getLong(field.getName()),field,instance);
                }
            }
        }
        return instance;
    }

    @SneakyThrows
    public static  <T> void setField(Object value, Field field, T instance){
        if(value!=null){
            field.setAccessible(true);
            field.set(instance,value);
        }
    }

}
